﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 跟单猿TMS_运单状态获取
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WaybillInfoToCRMController : ControllerBase
    {
        private readonly ILogger<WaybillInfoToCRMRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_t;


        public WaybillInfoToCRMController(ILogger<WaybillInfoToCRMRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_t = _configuration.GetConnectionString("WMSDbConnection_Test");

        }

        /// <summary>
        /// 跟单猿TMS_运单状态获取
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWaybillInfoToCRM([FromBody] WaybillInfoToCRMRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            WaybillInfoToWMSResponseDto re = new WaybillInfoToWMSResponseDto();
            WaybillInfoToCRMRequestDto pus = new WaybillInfoToCRMRequestDto();
            RaipiotTokenResponseDto tk = new RaipiotTokenResponseDto();

            pus.createTimeStart = MethodHelp.GetTimestampByDate(DateTime.Today);
            pus.createTimeEnd = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            try
            {
                Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                urldic = new Dictionary<string, string>(); //查询公用dic
                urldic.Add("function_description", "跟单猿_Token获取");//查看URL配置表地址描述
                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                if (url_dt.Rows.Count > 0)
                {
                    var reAgv2 = DB.httpGet(url_dt.Rows[0]["interface_url"].ToString(), "", "否");
                    RaipiotTokenResponseDto psp = JsonConvert.DeserializeObject<RaipiotTokenResponseDto>(reAgv2);
                    if (psp.status == 200)
                    {
                        urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic.Add("function_description", "跟单猿_运单状态获取");//查看URL配置表地址描述
                        DataTable url_dt2 = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                        if (url_dt2.Rows.Count>0)
                        {
                            string jsonText = JsonConvert.SerializeObject(pus);
                            var reAgv = DB.httpPost(url_dt2.Rows[0]["interface_url"].ToString(), jsonText, psp.data.token, "是");
                            Ri_WaybillInfoToCRMResponseDto psp2 = JsonConvert.DeserializeObject<Ri_WaybillInfoToCRMResponseDto>(reAgv);
                            if (psp2.status == 200)
                            {
                                Dictionary<string, string> dic = new Dictionary<string, string>(); //查询
                                Dictionary<string, string> dic_in = new Dictionary<string, string>(); //数据传入
                                if (psp2.data!=null)
                                {
                                    foreach (var item in psp2.data)
                                    {

                                        if (item.metadataName== "已提货"|| item.metadataName == "已签收")
                                        {
                                            dic = new Dictionary<string, string>();
                                            dic.Add("logisticsDetailsId", item.logisticsDetailsId);
                                            DataTable dt_check = MethodHelp.GetTableInfo("TMS0038", dic, con);//查询是否存在运单记录
                                            if (dt_check.Rows.Count <= 0)
                                            {
                                                int i = 1;
                                                string fileName1 = "";
                                                string fileName2 = "";
                                                string filePath1 = "";
                                                string filePath2 = "";


                                                foreach (var row in item.filePoolList)
                                                {
                                                    if (i == 1)
                                                    {
                                                        fileName1 = row.fileName;
                                                        filePath1 = row.filePath;
                                                    }
                                                    if (i == 2)
                                                    {
                                                        fileName2 = row.fileName;
                                                        filePath2 = row.filePath;
                                                    }


                                                    i++;
                                                }
                                                string operatorTime = MethodHelp.GetDateTimeMilliseconds(item.operatorTime).ToString();

                                                dic_in = new Dictionary<string, string>(); //数据传入
                                                dic_in.Add("logisticsDetailsId", item.logisticsDetailsId.ToString());
                                                dic_in.Add("transportOrderNo", item.transportOrderNo.ToString());
                                                dic_in.Add("carrierName", item.carrierName.ToString());
                                                dic_in.Add("carrierCode", item.carrierCode.ToString());
                                                dic_in.Add("planeNumber", item.planeNumber.ToString());
                                                dic_in.Add("driverMaName", item.driverMaName.ToString());
                                                dic_in.Add("driverMaPhone", item.driverMaPhone.ToString());
                                                dic_in.Add("metadataName", item.metadataName.ToString());
                                                dic_in.Add("status_g", item.status.ToString());
                                                dic_in.Add("operatorTime", operatorTime);
                                                dic_in.Add("sort", item.sort.ToString());
                                                dic_in.Add("goodsName", item.goodsName.ToString());
                                                dic_in.Add("goodsCode", item.goodsCode.ToString());
                                                dic_in.Add("goodsTotal", item.goodsTotal.ToString());
                                                dic_in.Add("orderNo", item.orderNo.ToString());
                                                dic_in.Add("subOrderNo", item.subOrderNo.ToString());
                                                dic_in.Add("saleNo", item.saleNo.ToString());
                                                dic_in.Add("subSaleNo", item.subSaleNo.ToString());
                                                dic_in.Add("loadType", item.loadType.ToString());
                                                dic_in.Add("fileName1", fileName1);
                                                dic_in.Add("filePath1", filePath1);
                                                dic_in.Add("fileName2", fileName2);
                                                dic_in.Add("filePath2", filePath2);
                                                dic_in.Add("deliverCompanyCode", item.deliverCompanyCode.ToString());
                                                dic_in.Add("deliverCompanyName", item.deliverCompanyName.ToString());
                                                dic_in.Add("loadAddress", item.loadAddress.ToString());
                                                dic_in.Add("deliverUserName", item.deliverUserName.ToString());
                                                dic_in.Add("deliverUserPhone", item.deliverUserPhone.ToString());
                                                strMsg = MethodHelp.InsertIntoTable("TMS0039", dic_in, con);
                                            }
                                        }
                                      
                                    }
                                }
                                                        
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
